package com.fjh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjh.constant.AuthConstant;
import com.fjh.domain.SysLoginUser;
import com.fjh.domain.User;
import com.fjh.mapper.SysLoginUserMapper;
import com.fjh.mapper.LoginUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.secret}")
    private String secret;

    @Value("${wx.token-url}")
    private String tokenUrl;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 这个才是登录
     * 和前端约定在请求头里面放一个标识
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (StringUtils.isEmpty(loginType)) {
            return null;
        }
        switch (loginType) {
            case AuthConstant.SYS_USER:
                // 查询后台的表
                SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                        .eq(SysLoginUser::getUsername, username)
                );
                if (!ObjectUtils.isEmpty(sysLoginUser)) {
                    // 查询权限
                    List<String> auths = sysLoginUserMapper.selectAuthById(sysLoginUser.getUserId());
                    if (!CollectionUtils.isEmpty(auths)) {
                        sysLoginUser.setAuths(auths);
                    }
                }
                return sysLoginUser;
            case AuthConstant.USER:
                // 查询前台会员的表
                //1.组装url参数
                String wxAuthUrl = String.format(tokenUrl, appid, secret, username);
                //2.发请求
                String wxAuthStr = restTemplate.getForObject(wxAuthUrl, String.class);
                JSONObject jsonObject = JSON.parseObject(wxAuthStr);
                //3.拿到openId
                String openid = jsonObject.getString("openid");
                if (StringUtils.hasText(openid)){
                    //微信那边已经授权成功了
                    //如果数据库有，则直接返回
                    //如果没有  我们需要给用户注册  因为微信小程序是默认注册的
                    User user = loginUserMapper.selectById(openid);
                    if (ObjectUtils.isEmpty(user)){
                        //帮用户注册  就是往数据库插入一条值
                       user =  createwxUser(openid);
                    }
                    return user;
                }
        }
        return null;
    }

    /**
     * 创建一个微信小程序用户
     * @return
     * @param openid
     */
    private User createwxUser(String openid) {
        //从request里面拿到我们的ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteAddr();
        User user = User.builder()
                .userId(openid)
                .status(1)
                .userRegtime(new Date())
                .modifyTime(new Date())
                .userLasttime(new Date())
                .score(0)
                .userRegip(ip)
                .userLastip(ip)
                .build();
        loginUserMapper.insert(user);
        return user;
    }
}
